/**
 * chenuu.com
 * 
 * @author  zhaoxu.com@gmail.com
 * @created 2012-11-3
 */
package com.chenuu.integration.httpclient;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

import com.chenuu.common.exceptions.ChenuuException;

/**
 *
 */
public class ChenuuHttpClient {

	private static final int MAX_CONNECTIONS_PER_HOST = 150;
	private static final int CONNECTION_TIMEOUT = 30000;
	private static final int SO_TIMEOUT = 30000;

	private static HttpClient client;

	static {
		MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
		HttpConnectionManagerParams paramshcmp = connectionManager.getParams();
		paramshcmp.setDefaultMaxConnectionsPerHost(MAX_CONNECTIONS_PER_HOST);
		paramshcmp.setConnectionTimeout(CONNECTION_TIMEOUT);
		paramshcmp.setSoTimeout(SO_TIMEOUT);

		// 忽略cookie，避免 Cookie rejected 警告
		HttpClientParams clientParams = new HttpClientParams();
		clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
		
		client = new HttpClient(clientParams, connectionManager);
	}

	public String post(String requestUrl, NameValuePair... nameValuePairs) {
		PostMethod method = new PostMethod(requestUrl);

		try {
			client.executeMethod(method);
		} catch (Exception e) {
			throw new ChenuuException("执行POST请求异常。", e);
		}

		try {
			return method.getResponseBodyAsString();
		} catch (IOException e) {
			throw new ChenuuException("获取响应数据异常。", e);
		}
	}
}
